layui.use(['table', 'form', 'layer', 'laypage'], function () {
    const table = layui.table;
    const form = layui.form;
    const layer = layui.layer;
    const laypage = layui.laypage;

    let allTeachers = [];  // 用于存储从后端获取的所有教师数据
    let currentLimit = 10; // 默认每页显示10条数据

    // 渲染教师表格
    const renderTable = (page = 1, limit = currentLimit) => {
        table.render({
            elem: '#teacherTable',
            data: allTeachers.slice((page - 1) * limit, page * limit),  // 前端分页，截取数据
            cols: [[
                {field: 'id', title: 'ID', width: 80, sort: true, hide: true},
                {field: 'employeeId', title: '员工编号', width: 110, sort: true},
                {field: 'name', title: '姓名', width: 120},
                {field: 'gender', title: '性别', width: 80},
                {field: 'subject', title: '学科', width: 120},
                {field: 'email', title: '邮箱', width: 200},
                {field: 'phone', title: '电话', width: 150},
                {field: 'salary', title: '薪资', width: 100},
                {field: 'department', title: '部门', width: 150},
                {field: 'address', title: '地址', width: 200},
                {field: 'isActive', title: '在职状态', width: 100, templet: function (d) {
                        return d.isActive ? '在职' : '离职';
                    }},
                {title: '操作', width: 150, toolbar: '#operationBar'}
            ]],
            page: false,  // 禁用默认分页
        });

        // 分页控制
        laypage.render({
            elem: 'pagination',  // 分页的容器
            count: allTeachers.length,  // 总数据条数
            limit: limit,  // 每页显示的数量
            curr: page,  // 当前页
            jump: function (obj, first) {
                if (!first) {
                    renderTable(obj.curr, obj.limit);  // 更新表格
                }
            }
        });
    };

    // 获取所有教师数据
    const fetchTeachers = () => {
        $.ajax({
            url: 'http://127.0.0.1:8080/teacher/teachers',
            type: 'GET',
            success: (res) => {
                if (res.code === 0) {
                    allTeachers = res.data.list;  // 保存所有数据
                    renderTable();  // 渲染表格
                } else {
                    layer.msg(res.message);
                }
            }
        });
    };


    // 初始化表格
    fetchTeachers();

    // 添加教师
    $('#addTeacherBtn').on('click', () => {
        layer.open({
            type: 1,
            title: '添加教师',
            area: ['500px', '600px'],
            content: $('#teacherFormTemplate').html(),
            success: (layero, index) => {
                form.render();
                form.on('submit(teacherFormSubmit)', function (data) {
                    const formData = data.field;

                    // 转换 isActive 字段为布尔值
                    formData.isActive = formData.isActive === "1";

                    $.ajax({
                        url: 'http://127.0.0.1:8080/teacher/add',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: (res) => {
                            if (res.code === 0) {
                                layer.msg('添加成功！');
                                fetchTeachers();  // 重新获取数据
                                layer.close(index);
                            } else {
                                layer.msg(res.message);
                            }
                        }
                    });
                    return false;
                });
            }
        });
    });

    // 监听工具条操作
    table.on('tool(teacherTable)', function (obj) {
        const data = obj.data;
        const event = obj.event;

        if (event === 'edit') {
            layer.open({
                type: 1,
                title: '编辑教师',
                area: ['500px', '600px'],
                content: $('#teacherFormTemplate').html(),
                success: (layero, index) => {
                    // 在编辑表单中填充数据，包含 id 和 employeeId
                    form.val('teacherForm', {
                        id: data.id,          // 填充 id
                        employeeId: data.employeeId,
                        name: data.name,
                        gender: data.gender,
                        subject: data.subject,
                        email: data.email,
                        phone: data.phone,
                        salary: data.salary,
                        department: data.department,
                        address: data.address,
                        isActive: data.isActive ? "1" : "0"
                    });
                    form.render();

                    form.on('submit(teacherFormSubmit)', function (data) {
                        const updatedData = data.field;

                        // 转换 isActive 字段为布尔值
                        updatedData.isActive = updatedData.isActive === "1";

                        $.ajax({
                            url: 'http://127.0.0.1:8080/teacher/update',
                            type: 'PUT',
                            contentType: 'application/json',
                            data: JSON.stringify(updatedData),
                            success: (res) => {
                                if (res.code === 0) {
                                    layer.msg('更新成功！');
                                    fetchTeachers();  // 重新获取数据
                                    layer.close(index);
                                } else {
                                    layer.msg(res.message);
                                }
                            }
                        });
                        return false;
                    });
                }
            });
        }
        else if (event === 'delete') {
            // 删除操作
            layer.confirm('确认删除此教师信息吗？', function (index) {
                $.ajax({
                    url: `http://127.0.0.1:8080/teacher/delete/${data.id}`,
                    type: 'DELETE',
                    success: (res) => {
                        if (res.code === 0) {
                            layer.msg('删除成功！');
                            fetchTeachers();  // 重新获取数据
                        } else {
                            layer.msg(res.message);
                        }
                    }
                });
                layer.close(index);
            });
        }
    });

    // 查询教师
    $('#searchTeacherBtn').on('click', () => {
        const employeeId = $('#employeeIdInput').val().trim();

        if (!employeeId) {
            // 如果搜索框为空，重新渲染表格以显示所有数据
            fetchTeachers();
        } else {
            // 如果搜索框有内容，执行普通的搜索功能
            $.ajax({
                url: `http://127.0.0.1:8080/teacher/teachers/employeeId/${employeeId}`,
                type: 'GET',
                success: (res) => {
                    if (res.code === 0) {
                        allTeachers = [res.data];  // 存储单个教师数据
                        renderTable();  // 渲染表格
                    } else {
                        layer.msg(res.message);
                        fetchTeachers();  // 重新获取所有数据
                    }
                },
                error: () => {
                    layer.msg('查询失败，请重试');
                    fetchTeachers();  // 重新获取所有数据
                }
            });
        }
    });
});
